<?php

namespace common\models;

use Yii;
use yii\db\ActiveQuery;
use yii\web\ServerErrorHttpException;

/**
 * This is the model class for table "order".
 *
 * @property int               $id
 * @property int               $uid 用户
 * @property int               $status 状态
 * @property string            $order_id 订单号
 * @property int               $type 类型
 * @property int               $good_id 商品
 * @property int               $number 数量
 * @property int               $total_price 总价
 * @property string            $location 收货地址
 * @property string            $notify 备注
 * @property int               $created_at 创建时间
 * @property int               $updated_at 最后更新时间
 * @property int               job_id 兼职或任务id
 *
 * @property User              $u
 * @property Goods             $good
 * @property UserConsumption[] $userConsumptions
 * @property PartTimeJob       $partTime
 * @property Mission           $mission
 */
class Order extends \yii\db\ActiveRecord
{
    const STATUS_PAY_SUCCESS = 10;
    const STATUS_NOT_PAY = 0;

//    const TYPE_PART_TIME_JOB = 1;
//    const TYPE_MISSION = 2;
    const TYPE_PART_TIME_POST = 1;
    const TYPE_PART_TIME_VIP = 2;
    const TYPE_MISSION_POST = 3;
    const TYPE_MISSION_SIGN_UP_CHARGE = 4;
    const TYPE_MISSION_SMS = 5;
    const TYPE_PART_TIME_SIGN_UP_CHARGE = 6;
    const TYPE_TAKE_MISSION = 7;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'order';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['uid', 'status', 'type', 'good_id', 'number', 'total_price', 'created_at', 'updated_at'], 'integer'],
            [['location', 'notify'], 'string', 'max' => 255],
            [
                ['uid'],
                'exist',
                'skipOnError'     => true,
                'targetClass'     => User::className(),
                'targetAttribute' => ['uid' => 'id']
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id'          => 'ID',
            'uid'         => '用户',
            'status'      => '状态',
            'type'        => '类型',
            'good_id'     => '商品',
            'number'      => '数量',
            'total_price' => '总价',
            'location'    => '收货地址',
            'notify'      => '备注',
            'created_at'  => '创建时间',
            'updated_at'  => '最后更新时间',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getU()
    {
        return $this->hasOne(User::className(), ['id' => 'uid']);
    }

    /**
     * @return ActiveQuery
     */
    public function getPartTime()
    {
        return $this->hasOne(PartTimeJob::className(), ['id' => 'job_id']);
    }

    /**
     * @return ActiveQuery
     */
    public function getMission()
    {
        return $this->hasOne(Mission::className(), ['id' => 'job_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserConsumptions()
    {
        return $this->hasMany(UserConsumption::className(), ['order_id' => 'id']);
    }

    public function getGood()
    {
        return $this->hasOne(Goods::className(), ['id' => 'good_id']);
    }

    public function beforeSave($insert)
    {
        if ($insert) {
            if ( ! isset($this->order_id)) {
                $this->order_id = uniqid();
            }
            $this->created_at = $this->updated_at = time();
        } else {
            $this->updated_at = time();
        }
        //TODO:这个做法有风险
        if (isset($this->number) && isset($this->good_id)) {
            $this->total_price = $this->number * $this->good->price;
        }

        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    /**
     * @param      $good_id
     * @param      $type
     * @param      $num
     * @param null $job_id
     *
     * @return Order
     * @throws ServerErrorHttpException
     */
    public static function generateOrderByGoodId($good_id, $type, $num, $order_id, $job_id = null)
    {
        $good            = Goods::findOne($good_id);
        $order           = new Order();
        $order->order_id = uniqid();
        $order->good_id  = $good_id;
        $order->status   = self::STATUS_NOT_PAY;
        $order->uid      = Yii::$app->getUser()->id;
        if ($job_id != null) {
            $order->job_id = $job_id;
        }
        $order->type        = $type;
        $order->number      = $num;
        $order->total_price = $num * $good->price;
//        $order->save(false);
        if ($order->save()) {
            return $order;
        } else {
            throw new ServerErrorHttpException('Generate order fail for unknow reason.' + PHP_EOL + $order->errors);
        }
    }


}
